<script setup>
import { onMounted, ref } from "vue";
import axios from "axios";
const tableData = ref([]); // 渲染表格数据
const twoData = ref([]); // 二维数组数据
const oneData = ref([]); // 原始数据
let pageNo = ref(1);
let pageSize = ref(10);
let total = ref(0);
let loading = ref(false);

onMounted(() => {
  init();
});

const init = async () => {
  loading.value = true;
  const { data } = await axios.get("/api/getList");
  loading.value = false;
  if (data.data.length) {
    total.value = data.data.length;
    oneData.value = data.data;
    resetData(oneData.value);
  }
};

const resetData = (data) => {
  twoData.value = avgFn(data, pageSize.value);
  render(pageNo.value);
};

const render = (page) => {
  tableData.value = twoData.value[page - 1];
};

const avgFn = (data, pageSize) => {
  let i = 0,
    result = [];
  while (i < data.length) {
    result.push(data.slice(i, i + pageSize));
    i = i + pageSize;
  }
  return result;
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  resetData(oneData.value);
};

const handleCurrentChange = (val) => {
  pageNo.value = val;
  render(pageNo.value);
};
</script>

<template>
  <el-space direction="vertical" :size="20">
    <el-table v-loading="loading" :data="tableData">
      <el-table-column prop="id" label="序 ID" width="180" />
      <el-table-column prop="name" label="名字" width="180" />
      <el-table-column prop="value" label="对应值" />
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[10, 100, 200, 300, 400]"
      small
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-space>
</template>
